import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client {
    public static void main(String[] args) {
        final String SERVER_IP = "127.0.0.1";
        final int SERVER_PORT = 12345;

        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT));

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter writer = new PrintWriter(socketChannel.socket().getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socketChannel.socket().getInputStream()));

            System.out.println("连接到服务器，可以开始发送消息：");
            String userInput;
            while ((userInput = reader.readLine()) != null) {
                writer.println(userInput);

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int bytesRead = socketChannel.read(buffer);
                if (bytesRead == -1) {
                    System.out.println("服务器关闭了连接");
                    break;
                }

                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                String response = new String(bytes).trim();
                System.out.println("服务器返回的消息：" + response);
            }

            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
